/*
 * Golazo GeoNotes
 * Copyright (C) 2009 Nakajiman Software Inc.
 * http://nakajiman.lrlab.to/
 *
 * This program is free software; you can redistribute it and/or modify
 * it under the terms of the GNU General Public License as published by
 * the Free Software Foundation; either version 3 of the License, or
 * (at your option) any later version.
 *
 * This program is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
 * GNU General Public License for more details.
 *
 * You should have received a copy of the GNU General Public License 
 * along with this program. If not, see <http://www.gnu.org/licenses/>.
 */

/**
 * save
 */
function save(data) {

  return Golazo.Proxy.dispatch(function(me) {

    if (!me)
      throw 'Forbidden';

    me.updateAttributes({
	  email: data.email
	  //timezone: data.timezon
	});
	
	var errors = me.getErrors();
	if (errors.length > 0)
	  throw new Error(errors.toSource());

  });

};
save.runat = 'server-proxy';

/**
 * serverload
 */
function serverload() {

  // GET
  Golazo.dispatch(function(request, response, me) {

    if (!me)
      return response.redirect('/signin.html?url=' + encodeURIComponent(request.uri));
    else if (!me.id)
      return response.redirect('/sigup.html');

    me.updateAttribute('expired', new Date());

    document.form.email.value = me.email;
	
	//$('option', document.form.timezone).each(function() {
	//  if (this.value == me.timezone)
	//    this.selected = true;
	//});

	$(document).me(me);

  // POST
  }, function(request, response, me) {
    throw 'Method Not Allowed';
  });

};

/**
 * load
 */
function load() {

  // info
  function info(text, fn) {
    var message = $('#message').text(text).slideDown(function() {
	  setTimeout(function() { message.slideUp(fn); }, 3000);
	});
  }

  $('a.me.canvasUrl', document.form).click(function() {
    $.settings(function() {
	  info('Thanks, your settings have been saved.', function() {
	    location.reload();
	  });
	});
	return false;
  });

  $(document.form).submit(function(e) {
    
	var error = $('div.message', this).hide();

	if (this.email.value !== '' && !Golazo.checkEmail(this.email.value))
	  return !error.text('Email is not a valid email address.').show();

    var icon = $(':submit', this)
	if (icon.hasClass('indicatorr'))
	  return false;
	icon.addClass('indicatorr');

	save.async([
      function() {
		icon.removeClass('indicatorr');
        info('Thanks, your settings have been saved.');
	  }, function(e) {
		icon.removeClass('indicatorr');
		error.text('Oops, there was a problem!').show();
	  }
    ], {
	  email: this.email.value
	});
      
    return false;
  });

};
load.runat = 'client';
